<?php
/*
  开发作者：南阳迈特网络科技有限公司
  QQ:794929988
*/

namespace addons\drama\listener;

use addons\drama\model\ResellerBind;
use addons\drama\model\ResellerLog;
use addons\drama\model\Share as ShareModel;
use addons\drama\model\User;
use think\Db;

/**
 * 分销
 */
class Reseller
{
    /**
     * 注册后推广关系保存
     * 注意user要求必须是登录用户，必须放到事务中执行
     * 使用spm方法拼接 shareUserId(分享者用户ID).page(页面类型:1=首页(默认),2=添加(手动)).pageId(页面ID).platform(平台渠道: 1=H5,2=微信公众号网页,3=微信小程序,4=Web,5=Admin,6=App).from(分享方式: 1=直接转发,2=海报,3=链接,4=补录)
     * 例 spm=258.1.0.3.2 即为ID为258用户通过微信小程序平台生成了首页分享海报
     */
    public function registerAfter($params)
    {
        extract($params);
        $share = ShareModel::add($spm, $platform);
        if ($share) {
            $share_id = $share['share_id'];
            \think\Hook::listen('share_success', $share_id);
            $user = User::info();
            User::where('id', $user->id)->update(['parent_user_id' => $share['share_id']]);
            \addons\drama\model\Reseller::share_user_reseller($share, $user);
        }
    }
    public function user_grade($user_id, $arr = [], $lv = [], $reseller_user_arr = [])
    {
        // 查询所有的比自身等级大的数据
        $reseller_user = Db::name('drama_reseller_user')
            ->where('user_id', $user_id)
            ->where('type', 1)
            ->find();
        if ($reseller_user) {
            $reseller_bind = ResellerBind::where('user_id', $reseller_user['reseller_user_id'])->find()->toArray();
            $user_info = Db::name('user')->find($reseller_user['reseller_user_id']);
            if ($reseller_bind && $user_info) {
                if ($reseller_bind['level'] <= 3) {
                    if ($lv[count($lv) - 1] <= $reseller_bind['level'] || count($lv) == 0) {
                        if (!in_array($reseller_bind['level'], $lv)) {
                            $lv[] = $reseller_bind['level'];
                            $arr[$reseller_bind['level']] = $reseller_user['reseller_user_id'];
                            $reseller_user_arr[$reseller_bind['level']] = $reseller_user;
                        }
                    }
                    return $this->user_grade($reseller_user['reseller_user_id'], $arr, $lv, $reseller_user_arr);
                }
            }
        }
        return [$arr, $reseller_user_arr];
    }
    /**
     * 订单完成后
     * [order, order_type]
     */
    public function finishAfter($param)
    {
        extract($param);
        if (in_array($order['status'], [1, 2])) {
            $reseller_user = Db::name('drama_reseller_user')
                ->where('user_id', $order['user_id'])
                ->where('type', 1)
                ->find();
            // dump($order_type);
            $option = 0;
            if ($order_type == 'reseller') {
            // dump(123);
                $option = Db::name('drama_reseller')->where(['id' => $order['reseller_id']])->value('option');
                Db::name('user')->where('id', $order['user_id'])->setInc('option', $option);
                if ($option > 0) {
                    $Optionmodel = new \app\admin\model\drama\Option;
                    $option_save = [];
                    $option_save['site_id'] = $order['site_id'];
                    $option_save['title'] = '后台赠送';
                    $option_save['desc'] = '后台赠送';
                    $option_save['option'] = $option;
                    $option_save['status'] = 0;
                    $option_save['weigh'] = 0;
                    $option_save['uid'] = $order['user_id'];
            // dump(123);
                    $Optionmodel->save($option_save);
            // dump(123);
                }
            }
            list($arr, $reseller_user_arr) = $this->user_grade($reseller_user['user_id']);
            $level = 1;
            $option1 = array_sum(Db::name('drama_option')->where(['site_id' => $order['site_id'], 'status' => '1'])->column('option'));
            $option0 = array_sum(Db::name('drama_option')->where(['site_id' => $order['site_id'], 'status' => '0'])->column('option'));
            $a = bcsub($option1, $option0, 2);
            // 只有直推有期权制
            if ($order_type == 'reseller') {
                if ($option == $option0) {
                    $option = 0;
                } else if ($a < 0) {
                    $option = 0;
                } else if (bcsub($a, $option, 2) < 0) {
                    $option = $a;
                }
            } else {
                $option = 0;
            }
            $d_r_sum = array_sum(Db::name('drama_reseller')->where(['status' => 'normal', 'level' => ['in', '2,3']])->column('range'));

            foreach ($arr as $k => $v) {
                $reseller_bind = ResellerBind::where('user_id', $v)->find()->toArray();
                $drama_reseller = Db::name('drama_reseller')->find($reseller_bind['reseller_id']);
                if ($order_type == 'usable') {
                    $drama_reseller['direct'] = $drama_reseller['direct_pf'];
                    $drama_reseller['range'] = $drama_reseller['range_pf'];
                    $drama_reseller['indirect'] = $drama_reseller['indirect_pf'];
                    $d_r_sum = array_sum(Db::name('drama_reseller')->where(['status' => 'normal', 'level' => ['in', '2,3']])->column('range_pf'));
                }
                $reseller_user = $reseller_user_arr[$k];
                if ($drama_reseller['level'] == 1) {
                    $drama_reseller['range'] = $drama_reseller['direct'];
                    // $drama_reseller['range'] = $drama_reseller['range'] == 0 ? $drama_reseller['direct'] : $drama_reseller['range'];
                }
                if ($drama_reseller['range'] > 0) {
                    $ratio = $drama_reseller['range'];
                    if ($order_type == 'usable') {
                        if(in_array(1,$key_arr) && in_array(3,$key_arr) && !in_array(2,$key_arr)){
                            $ratio=$d_r_sum;
                        }
                    }else{
                        if ($drama_reseller['level'] == 2) {
                            $d_r_sum -= $ratio;
                        }
                        if ($drama_reseller['level'] == 3) {
                            $ratio = $d_r_sum;
                        }
                    }
                    if ($level == 1) {
                        $ratio = $drama_reseller['direct'];
                        $money = bcmul($order['pay_fee'], $ratio / 100, 2);
                        $type = 'direct';
                        $msg = '直接销售奖';
                    } else {
                        // dump($d_r_sum);
                        $money = bcmul($order['pay_fee'], $ratio / 100, 2);
                        $type = 'indirect_t_l';
                        $msg = '极差奖金';
                        $option = 0;
                    }
                    $level++;
                    $params = [
                        'reseller_user_id' => $v,
                        'site_id' => $order['site_id'],
                        'user_id' => $order['user_id'],
                        'pay_money' => $order['pay_fee'],
                        'order_type' => $order_type,
                        'order_id' => $order['id'],
                        'type' => $type,
                        'ratio' => $ratio,
                        'money' => $money,
                        'option' => $option,
                        // 'msg' => $msg,
                    ];
                    $this->reseller_log_add($params, $money, $reseller_user, $msg, $option);
                    // 查询同级的上级
                    $reseller_user = Db::name('drama_reseller_user')
                        ->where('user_id', $reseller_user['reseller_user_id'])
                        ->where('type', 1)
                        ->find();
                    $user_info = Db::name('user')->find($reseller_user['reseller_user_id']);
                    if ($reseller_user && $user_info) {
                        $reseller_bind = ResellerBind::where('user_id', $reseller_user['reseller_user_id'])->where('level', $k)->find();
                        if ($reseller_bind) {
                            $drama_reseller = Db::name('drama_reseller')->find($reseller_bind['reseller_id']);
                            if ($order_type == 'usable') {
                                $drama_reseller['direct'] = $drama_reseller['direct_pf'];
                                $drama_reseller['range'] = $drama_reseller['range_pf'];
                                $drama_reseller['indirect'] = $drama_reseller['indirect_pf'];
                            }
                            // 如果有同级的上级 平级返佣
                            $money = bcmul($params['money'], $drama_reseller['indirect'] / 100, 2);
                            $params = [
                                'reseller_user_id' => $reseller_bind['user_id'],
                                'site_id' => $order['site_id'],
                                'user_id' => $order['user_id'],
                                'pay_money' => $order['pay_fee'],
                                'order_type' => $order_type,
                                'order_id' => $order['id'],
                                'type' => 'indirect',
                                'ratio' => $drama_reseller['indirect'],
                                'money' => $money,
                                'option' => 0,
                                // 'msg' => '平级管理奖',
                            ];
                            $this->reseller_log_add($params, $money, $reseller_user, $msg, $option);
                        }
                    }
                }
            }
        }
    }
    public function reseller_log_add($params_class, $reseller_money_class, $reseller_user_class, $msg_class, $option)
    {
        // dump($params_class);
        $reseller_log = ResellerLog::create($params_class);
        // 查询齐全值够不够
        if ($params_class['order_type'] == 'usable') {
            if ($reseller_money_class > 0) {
                \addons\drama\model\User::money_pf(
                    $reseller_money_class,
                    $reseller_user_class['reseller_user_id'],
                    'commission_income',
                    $reseller_log->id,
                    $msg_class,
                    [
                        'reseller_log_id' => $reseller_log->id,
                        'user_id' => $reseller_log->user_id,
                        'parent_id' => $reseller_user_class['parent_id'],
                        'reseller_user_id' => $reseller_log->reseller_user_id
                    ],
                    $option,
                    $params_class['site_id']
                );
            }
        } else {
            if ($reseller_money_class > 0) {
                \addons\drama\model\User::money(
                    $reseller_money_class,
                    $reseller_user_class['reseller_user_id'],
                    'commission_income',
                    $reseller_log->id,
                    $msg_class,
                    [
                        'reseller_log_id' => $reseller_log->id,
                        'user_id' => $reseller_log->user_id,
                        'parent_id' => $reseller_user_class['parent_id'],
                        'reseller_user_id' => $reseller_log->reseller_user_id
                    ],
                    $option,
                    $params_class['site_id']
                );
            }
        }
    }
}
